package com.hjq.fcloud.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.hjq.fcloud.R
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.config.CommonValueType
import com.hjq.fcloud.config.Config
import com.hjq.fcloud.http.api.GetListJsonApi
import com.hjq.fcloud.http.api.GetSelectCodeApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.presenter.CommonListPresenter
import com.hjq.fcloud.presenter.SelectPresenter
import com.hjq.fcloud.ui.factory.CommonViewSupport
import com.hjq.fcloud.ui.factory.OnChangeListener
import com.hjq.fcloud.ui.factory.OnSelectChangeListener
import com.hjq.bar.TitleBar
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback

/**
 * 公共查询
 */
class CommonListQueryActivity : AppActivity() {

    private lateinit var mTitleBar: TitleBar
    private lateinit var mTitlte: String

    //保存的查询字段，比如project="1001",name="张三"      （保存的是id，主要接口需要）
    private lateinit var mQueryOrderMap: HashMap<String, String>
    //保存的查询字段对应的真正名字，用户回显，比如project="环球中心",name="张三"
    private lateinit var mQueryOrderMapValue: HashMap<String, String>

    //列表显示的json数组
    private lateinit var mTempleJson: List<GetListJsonApi.DataDTO.JsonDTO>

    private lateinit var mResetView: TextView
    private lateinit var mQueryView: TextView
    private lateinit var mParentView: LinearLayout

    //用于清除查询
    private var mItemViewCacheList: ArrayList<View> = ArrayList()

    private lateinit var mPresenter:CommonListPresenter

    override fun getLayoutId(): Int {
        return R.layout.activity_common_list_quert
    }

    override fun initView() {
        mTitleBar = findViewById(R.id.id_title_bar)!!
        mQueryView = findViewById(R.id.id_query_tv)!!
        mQueryView.setOnClickListener(View.OnClickListener {
            var intent = Intent()
            intent.putExtra(INTENT_KEY_QUERY_MAP, mQueryOrderMap)
            intent.putExtra(INTENT_KEY_QUERY_MAP_VALUE, mQueryOrderMapValue)
            setResult(Activity.RESULT_OK, intent)
            finish()
        })
        mResetView = findViewById(R.id.id_reset_tv)!!
        mResetView.setOnClickListener(View.OnClickListener {
            clearQuery();
        })
        mParentView = findViewById(R.id.id_parent_ll)!!
    }

    private fun clearQuery() {
        resetMap(mQueryOrderMap)
        resetMap(mQueryOrderMapValue)

        mItemViewCacheList.forEach {
            if (it is TextView) {
                it.setText("")
            } else if (it is EditText) {
                it.setText("")
            }
        }
    }

    @SuppressLint("NewApi")
    private fun resetMap(map: HashMap<String, String>) {
        if (map != null) {
            map.filterKeys {
                !it.equals(Config.SERVER_LIST_KEY_PAGE) && !it.equals(Config.SERVER_LIST_KEY_LIMIT)
            }.filter {  (k,v)->
                !mPresenter.notResetCondition(mTempleJson ,k)
            }.forEach { key, value ->
                map[key] = ""
            }
        }
    }

    override fun initData() {
        mPresenter = CommonListPresenter()
        this.mTitlte = intent.getStringExtra(INTENT_KEY_TITLE)!!
        this.mQueryOrderMap = intent.getSerializableExtra(INTENT_KEY_QUERY_MAP) as HashMap<String, String>
        this.mQueryOrderMapValue = intent.getSerializableExtra(INTENT_KEY_QUERY_MAP_VALUE) as HashMap<String, String>

        var stempleJsonStr = intent.getSerializableExtra(INTENT_KEY_SHOW_JSON_STR)
        if (stempleJsonStr != null) {
            mTempleJson = JSON.parseArray(stempleJsonStr.toString(), GetListJsonApi.DataDTO.JsonDTO::class.java)
        }
        mTitleBar.setTitle(mTitlte + "查询")

        addChildView();
    }

    @SuppressLint("NewApi")
    private fun addChildView() {
        //准备： 上个界面将get_list_json.php里面的templeJson和条件（拼装为一个map）传入到当前界面，
        //1. 循环遍历templeJson
        //2. 如果hideInSearch=0则通过CommonViewFactory得到对应的valueType的View
        //3. 在CommonViewFactory中给view设置监听，有输入则回调到activity，并回调对应的textview，edittext，保存到view的集合views
        //4. 点击重置按钮则遍历views，设置为空
        //5. 点击确定按钮将map setResult给上一个界面
        //6. 通过map设置到入参data里面，重新刷新上个界面
        if (mTempleJson != null) {
            for (it in mTempleJson) {
                if (it.hideInSearch == 0) {
                    var dataIndex = it.dataIndex

                    var defaultHint = it.title
                    var defaultInput = mQueryOrderMap.get(dataIndex)

                    //普通输入框
                    if (TextUtils.isEmpty(it.valueType) || it.valueType.equals(CommonValueType.VALUE_TYPE_TEXT)) {
                        var itemView = CommonViewSupport().getInputView(this, defaultHint, defaultInput, object : OnChangeListener {
                            override fun onFindView(vararg itemViews: View) {
                                var itemView = itemViews[0]
                                if (!mItemViewCacheList.contains(itemView)) {
                                    mItemViewCacheList.add(itemView)
                                }
                            }

                            override fun onValueChange(vararg str: String) {
                                mQueryOrderMap.put(dataIndex, str[0])
                            }
                        });
                        mParentView.addView(itemView)
                    } else if (it.valueType.equals(CommonValueType.VALUE_TYPE_SELECT)) {
                        var mSelectView = CommonViewSupport()
                        var itemView = mSelectView.getSelectView(this@CommonListQueryActivity, defaultHint, getRealValueByDataIndex(it, defaultInput), object : OnSelectChangeListener {
                            override fun onFindView(vararg itemViews: View) {
                                var itemView = itemViews[0]
                                if (!mItemViewCacheList.contains(itemView)) {
                                    mItemViewCacheList.add(itemView)
                                }
                            }

                            override fun onValueChange(str: String, pos: Int, codeStr: String) {
                                mQueryOrderMap.put(dataIndex, codeStr)
                                mQueryOrderMapValue.put(it.dataIndex, str)
                            }
                        });
                        mParentView.addView(itemView)

                        SelectPresenter.getSelect(this,it.selectCode,{
                            mSelectView.refershSelectViewData(it)
                        })
                    } else if (it.valueType.equals(CommonValueType.VALUE_TYPE_DATE_RANGE)) {
                        var mSelectDataView = CommonViewSupport()
                        var itemView = mSelectDataView.getSelectDateView(this@CommonListQueryActivity, defaultHint, defaultInput, object : OnChangeListener {
                            override fun onFindView(vararg itemViews: View) {
                                var itemView = itemViews[0]
                                if (!mItemViewCacheList.contains(itemView)) {
                                    mItemViewCacheList.add(itemView)
                                }
                            }

                            override fun onValueChange(vararg str: String) {
                                mQueryOrderMap.put(dataIndex, str[0])
                            }
                        });
                        mParentView.addView(itemView)
                    } else if (it.valueType.equals(CommonValueType.VALUE_TYPE_TREE)) {
                        var mSelectDataView = CommonViewSupport()
                        var itemView = mSelectDataView.getTreeView(this@CommonListQueryActivity, defaultHint, getRealValueByDataIndex(it, defaultInput), it.selectCode, object : OnChangeListener {
                            override fun onValueChange(vararg str: String) {
                                mQueryOrderMap.put(dataIndex, str[0])
                                mQueryOrderMapValue.put(it.dataIndex, str[1])
                            }

                            override fun onFindView(vararg itemViews: View) {
                                var itemView = itemViews[0]
                                if (!mItemViewCacheList.contains(itemView)) {
                                    mItemViewCacheList.add(itemView)
                                }
                            }
                        });
                        mParentView.addView(itemView)
                    }else if (it.valueType.equals(CommonValueType.VALUE_TYPE_SEARCH_TREE)) {
                        var mSelectDataView = CommonViewSupport()
                        var itemView = mSelectDataView.getSearchTreeView(this@CommonListQueryActivity, defaultHint, getRealValueByDataIndex(it,defaultInput), it.tree_limit_info, object : OnChangeListener {
                            override fun onValueChange(vararg str: String) {
                                mQueryOrderMap.put(dataIndex, str[0])
                                mQueryOrderMapValue.put(it.dataIndex, str[1])
                            }

                            override fun onFindView(vararg itemViews: View) {
                                var itemView = itemViews[0]
                                if (!mItemViewCacheList.contains(itemView)) {
                                    mItemViewCacheList.add(itemView)
                                }
                            }
                        });
                        mParentView.addView(itemView)
                    }
                }
            }
        }
    }

    /**
     * 通过dataIndex获取真实的值
     */
    private fun getRealValueByDataIndex(item: GetListJsonApi.DataDTO.JsonDTO, defaultInput: String?): String? {
        if (!TextUtils.isEmpty(defaultInput)) {
            var cacheStr: String? = mQueryOrderMapValue.get(item.dataIndex)
            return cacheStr
        }
        return ""
    }

    companion object {
        const val INTENT_KEY_TITLE = "intent_key_title"

        //查询条件
        const val INTENT_KEY_QUERY_MAP = "intent_key_query_map"

        //查询条件对应的值，部分需要，比如tree或者单选框的code对应的值，保存了不用反向查找了
        const val INTENT_KEY_QUERY_MAP_VALUE = "intent_key_query_map_value"
        const val INTENT_KEY_SHOW_JSON_STR = "intent_key_show_json_str"
    }

    override fun onDestroy() {
        super.onDestroy()
        mItemViewCacheList.clear()
        mQueryOrderMap.clear()
        mQueryOrderMapValue.clear()
    }

}